/**
 * Created by HAIWEI-LC on 2019/10/23
 */
package com.hw.paltfrom.utils;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.hw.paltfrom.exception.HWSystemException;
import com.hw.paltfrom.rescode.HWSystemCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class TokenUtil {
    private static Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    /**
     * 计算token，将token放置在session里,防止表单重复提交
     * @param request
     */
    public static String getToken(HttpServletRequest request,String sessionKey,String password) {

        // 计算token，将token放置在session里和返回页面，防止表单重复提交
        String submitToken = UUID.randomUUID().toString()+Base64Util.encode(sessionKey+password);
        request.getSession().setAttribute(sessionKey, submitToken);

        return submitToken;
    }
    public static String getToken(String sessionKey,String password) {

        // 计算token，将token放置在session里和返回页面，防止表单重复提交
        String submitToken = UUID.randomUUID().toString()+Base64Util.encode(sessionKey+password);
//        request.getSession().setAttribute(sessionKey, submitToken);

        return submitToken;
    }
    /*
     *
     */
    public static void tokenCheck(String submitToken, HttpServletRequest request,String sessionKey) {
        logger.debug("校验的新sessionid:{}",request.getSession().getId());
        String tokenValue = (String) request.getSession().getAttribute(sessionKey);
        logger.debug("校验token,参数：[submitToken:"+submitToken+",tokenValue:"+tokenValue+"]");
        if (StringUtils.isBlank(submitToken)) {
            throw new HWSystemException(HWSystemCode.DAO_ERROR);
        }

        // 参数、session中都没用token值提示错误
        if (StringUtils.isBlank(submitToken) && StringUtils.isBlank(tokenValue)) {
            throw new HWSystemException(HWSystemCode.FAIL);
        } else if ((!StringUtils.isBlank(submitToken)) && StringUtils.isBlank(tokenValue)) {
            throw new HWSystemException(HWSystemCode.NOT_REPEAT_SUBMMIT);
        }

        synchronized (tokenValue) {
            tokenValue = (String) request.getSession().getAttribute(sessionKey);
            if (tokenValue.equalsIgnoreCase(submitToken)) {
                request.getSession().removeAttribute(sessionKey);
                return;
            } else {
                throw new HWSystemException(HWSystemCode.NOT_REPEAT_SUBMMIT);
            }
        }
    }
}
